package aliyun

import (
	"fmt"
	"log"
	"os"
	"workflow/store"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/joho/godotenv"
)

var (
	AccessKey       string
	AccessKeySecret string
	OssEndPoint     string
	BucketName      string
)

type AliyunOss struct {
	client *oss.Client
}

var _ store.Uploader = &AliyunOss{}

func (s *AliyunOss) Upload(bucketName, objectKey, fileName string) error {

	bucket, err := s.client.Bucket(BucketName)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	err = bucket.PutObjectFromFile(objectKey, fileName)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	time := 60 * 60
	downloadUrl, err := bucket.SignURL(fileName, oss.HTTPGet, int64(time))
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println(fileName, "上传成功")
	fmt.Printf("%s的下载的地址为: %s, 下载链接%ds后失效", fileName, downloadUrl, time)
	return nil
}

func NewAliyunOss(OssEndPoint, AccessKey, AccessKeySecret string) (*AliyunOss, error) {
	c, err := oss.New(OssEndPoint, AccessKey, AccessKeySecret)
	if err != nil {
		return nil, err
	}
	return &AliyunOss{
		client: c,
	}, nil
}

func init() {
	err := godotenv.Load("../../unit_test.env")
	if err != nil {
		log.Fatal("Error loading .env file")
	}
	AccessKey = os.Getenv("ALI_AK")
	AccessKeySecret = os.Getenv("ALI_SK")
	OssEndPoint = os.Getenv("ALI_OSS_ENDPOINT")
	BucketName = os.Getenv("ALI_BUCKET_NAME")
}
